package com.yuven.baselib.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.text.TextUtils;

import com.yuven.baselib.utils.security.Base64;

/**
 * 手机，APP，环境监测
 */
public class AppHelper {

    /**
     * 是否是开发模式
     *
     * @return
     */
    public static boolean isDebug() {
        ApplicationInfo info = ToolsKit.getClient().getApplicationInfo();
        return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
    }


    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * App签名校验
     *
     * @param context                context
     * @param appEncodedSignature app预置的签名值（加密后）
     * @return true-验签成功，false-验签失败
     */
    public static boolean checkAppSignature(Context context, String appEncodedSignature) {
        if (context == null || TextUtils.isEmpty(appEncodedSignature)) {
            return false;
        }
        boolean isSignatureOk = false;
        PackageManager pm = context.getPackageManager();
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            if (pi != null) {
                Signature[] s = pi.signatures;
                if (s != null && s.length > 0) {
                    String hashCodeSignature = s[0].hashCode() + "";
                    String signatureEncoded = Base64.encode(hashCodeSignature.getBytes());
                    if (appEncodedSignature.equals(signatureEncoded)) {
                        isSignatureOk = true;
                    }
                }
            }
        } catch (Exception e) {
            isSignatureOk = false;
            e.printStackTrace();
        }
        return isSignatureOk;
    }

}
